package com.lan.support.boot;

import com.lan.app.utils.Deploy;
import com.lan.support.response.ex.Ex;
import com.lan.support.response.ex.SExCode;
import com.lan.support.response.json.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;

//@RestControllerAdvice
@ControllerAdvice
public class GlobalExceptionHandler {

    Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    @ResponseBody
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NoHandlerFoundException.class)
    public Object handle404Exception(NoHandlerFoundException e) {
        Object v = Deploy.getInstance().exec();
        if (v != null) {
            return R.OK(v);
        }
        return R.Fail("404");
    }


    /**
     * 返回的Map对象会被@ResponseBody注解转换为JSON数据返回
     *
     * @return
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Object handleException(HttpServletRequest request, Exception ex) {
        if (ex instanceof Ex) {
            Ex e = (Ex) ex;
            logger.error("Ex URL:" + request.getServletPath(), e.getMessage());
            if (((Ex) ex).getEx() instanceof SExCode) {
                return R.Fail("系统异常，请稍后再试");
            } else {
                return R.Fail(e);
            }
        } else {
            logger.error("Ex URL:" + request.getServletPath(), ex);
            return R.Fail(SExCode.SYS);
        }
    }

}
